package com.cow.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cow.pojo.Bill;
import com.cow.pojo.Good;
import com.cow.pojo.OrderGood;
import com.cow.pojo.Orders;
import com.cow.service.BillService;
import com.cow.service.GoodService;
import com.cow.service.OrderGoodService;
import com.cow.service.OrderService;
import com.cow.util.PayUtilBean;
import com.cow.util.WXPayUtilBean;
import com.cow.util.WXUtil;

import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 光环and鬼泣
 * @version 2018年6月8日 下午3:47:05
 */
@Controller
public class WXPayController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderGoodService orderGoodService;
	@Autowired
	private GoodService goodService;
	@Autowired
	private BillService billService;

	@ApiOperation(value = "订单", notes = "获取openid")
	@ResponseBody
	@RequestMapping(value = "createOrder.action", method = RequestMethod.POST)
	public JSONObject createOrder(HttpServletRequest req, HttpServletResponse rep, @RequestParam("code") String code,
			@RequestParam("userId") String userId, @RequestParam("orderId") String orderId,
			@RequestParam("addressId") String addressId, @RequestParam("totalPrice") String totalPrice,
			@RequestParam(value = "orderNotes", required = false) String orderNotes,
			@RequestParam("goodList") String goodList) throws Exception {
		Orders order1 = orderService.getOrder(orderId);
		if (order1 != null) {
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("code", "-1");
			map1.put("result", "请勿重复提交");
			return JSONObject.fromObject(map1);
		} else {
			String openid = WXUtil.getOpenid(code);
			Orders order = new Orders();
			order.setAddressId(addressId);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String addTime = sdf.format(date);
			order.setUserId(userId);
			order.setOrderAddtime(addTime);
			order.setOrderId(orderId);
			order.setOrderNotes(orderNotes);
			order.setOrderState("未付款");
			order.setOrderTotalprice(totalPrice);
			orderService.createOrder(order);
			JSONArray JSONgoodList = JSONArray.fromObject(goodList);
			for (int i = 0; i < JSONgoodList.size(); i++) {
				JSONObject object = JSONgoodList.getJSONObject(i);
				Good good = goodService.getGoodDetail(object.getString("goodId"));
				OrderGood orderGood = new OrderGood();
				orderGood.setGoodDescribe(good.getGoodDescribe());
				orderGood.setGoodDetail(good.getGoodDetail());
				orderGood.setGoodId(good.getGoodId());
				orderGood.setGoodName(good.getGoodName());
				orderGood.setGoodNumber(object.getString("goodNumber"));
				orderGood.setGoodPicture(good.getGoodPicture());
				orderGood.setGoodPrice(good.getGoodPrice());
				orderGood.setOrderId(orderId);
				orderGoodService.insertOrderGood(orderGood);
			}
			String nonce_str = WXUtil.getRandomStr();
			String out_trade_no = System.currentTimeMillis() + "";
			String spbill_create_ip = WXUtil.getIP(req);
			Map<String, String> map = new HashMap<String, String>();
			String appid = "wx39e04b55ecedf4c6";
			String mch_id = "1507091541";
			String key = "jnyczcwlkjyxgsykh178641951651234";
			String body = "test";
			map.put("appid", appid);
			map.put("mch_id", mch_id);
			map.put("nonce_str", nonce_str);
			map.put("body", body);
			map.put("total_fee", String.valueOf((int) (Double.parseDouble(totalPrice) * 100)));
			map.put("openid", openid);
			map.put("spbill_create_ip", spbill_create_ip);
			map.put("trade_type", "JSAPI");
			map.put("notify_url", "http://halo.natapp1.cc/cow/payReturn.action");
			map.put("out_trade_no", out_trade_no);
			String sign = WXUtil.sign(map, key);
			map.put("sign", sign);
			String data = WXUtil.getXML(map, key);
			PayUtilBean payUtilBean = WXUtil.sendRequet(data);
			String timeStamp = System.currentTimeMillis() + "";
			String nonceStr = WXUtil.getRandomStr();
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("appId", appid);
			map1.put("timeStamp", timeStamp);
			map1.put("nonceStr", nonceStr);
			map1.put("package", "prepay_id=" + payUtilBean.getPrepay_id());
			map1.put("signType", "MD5");
			WXPayUtilBean WXPayUtilBean = new WXPayUtilBean(timeStamp, nonceStr, WXUtil.sign(map1, key),
					"prepay_id=" + payUtilBean.getPrepay_id(), appid);
			System.out.println(appid + " " + timeStamp + " " + nonceStr + " " + payUtilBean.getPrepay_id() + " "
					+ WXUtil.sign(map, key));
			return JSONObject.fromObject(WXPayUtilBean);
		}

	}

	@ApiOperation(value = "微信支付确定接口", notes = "微信支付确定接口")
	@ResponseBody
	@RequestMapping(value = "/pay.action", method = RequestMethod.POST)
	public JSONObject pay(HttpServletRequest req, HttpServletResponse rep, @RequestParam("orderId") String orderId)
			throws Exception {
		Orders orders = orderService.getOrder(orderId);
		orders.setOrderState("已付款");
		int result = orderService.updataOrer(orders);
		Bill bill = new Bill();
		bill.setMoney(orders.getOrderTotalprice());
		bill.setOrderId(orders.getOrderId());
		bill.setUserId(orders.getUserId());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String addTime = sdf.format(date);
		bill.setTime(addTime);
		result = result + billService.insertBill(bill);
		Map<String, String> data = new HashMap<String, String>();
		if (result == 2) {
			data.put("result", "订单支付成功");
			data.put("code", "0");
		} else {
			data.put("result", "订单支付失败");
			data.put("code", "-1");
		}
		JSONObject datas = JSONObject.fromObject(data);
		return datas;

	}

	/**
	 * @param req
	 * @param rep
	 * @Description 微信支付回调地址
	 * @throws Exception
	 */
	@ApiOperation(value = "微信支付回调地址", notes = "微信支付回调地址")
	@RequestMapping(value = "/payReturn", method = RequestMethod.POST)
	public void payReturn(HttpServletRequest req, HttpServletResponse rep) throws Exception {

	}

}
